import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { authApi } from '../services/api'

interface User {
  id: number
  username: string
  email?: string
  phone?: string
  nickname?: string
  avatar?: string
  role: string
}

interface AuthState {
  user: User | null
  token: string | null
  isAuthenticated: boolean
  loading: boolean
  login: (username: string, password: string) => Promise<void>
  register: (userData: {
    username: string
    password: string
    email?: string
    phone?: string
    nickname?: string
  }) => Promise<void>
  logout: () => void
  fetchProfile: () => Promise<void>
  updateProfile: (data: any) => Promise<void>
  setUser: (user: User) => void
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      loading: false,

      login: async (username: string, password: string) => {
        set({ loading: true })
        try {
          const response = await authApi.login({ username, password })
          const { user, token } = response.data
          localStorage.setItem('token', token)
          set({ user, token, isAuthenticated: true, loading: false })
        } catch (error) {
          set({ loading: false })
          throw error
        }
      },

      register: async (userData) => {
        set({ loading: true })
        try {
          const response = await authApi.register(userData)
          const { user, token } = response.data
          localStorage.setItem('token', token)
          set({ user, token, isAuthenticated: true, loading: false })
        } catch (error) {
          set({ loading: false })
          throw error
        }
      },

      logout: () => {
        authApi.logout()
        set({ user: null, token: null, isAuthenticated: false })
      },

      fetchProfile: async () => {
        try {
          const { data } = await authApi.getCurrentUser()
          set({ user: data })
        } catch (error) {
          set({ user: null, token: null, isAuthenticated: false })
          throw error
        }
      },

      updateProfile: async (data) => {
        try {
          const { data: updatedUser } = await authApi.updateProfile(data)
          set({ user: updatedUser })
        } catch (error) {
          throw error
        }
      },

      setUser: (user: User) => {
        set({ user, isAuthenticated: !!user })
      },
    }),
    {
      name: 'auth-store',
      partialize: (state) => ({
        user: state.user,
        token: state.token,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
)